import {
	wx_paas_app_path
} from '@/api/index.js'
const pendingRequests = {}

export const refreshPageConfig = async () => {
	const str = wx.getStorageSync('update_date')
	const {
		app_path,
		update_date
	} = await wx_paas_app_path({
		update_date: str
	})
	wx.setStorageSync('page-config', JSON.stringify(app_path))
	update_date && wx.setStorageSync('update_date', update_date)
}

export const getPageConfigData = async () => {
	const pageConfig = wx.getStorageSync('page-config')
	if (!pageConfig) {
		if (!pendingRequests['wx_paas_app_path']) {
			pendingRequests['wx_paas_app_path'] = wx_paas_app_path()
		}
		const {
			app_path,
			update_date
		} = await pendingRequests['wx_paas_app_path']
		delete pendingRequests['wx_paas_app_path']
		wx.setStorageSync('page-config', JSON.stringify(app_path))
		update_date && wx.setStorageSync('update_date', update_date)
		return app_path
	}
	return JSON.parse(pageConfig)
}

// 获取当前页面所有的数据
export async function getCurrentPageConfig() {
	const pageList = getCurrentPages()
	const currentPage = pageList[pageList.length - 1]
	const pageConfig = await getPageConfigData()
	const currentPageConfig = pageConfig.find(item => item.path === currentPage.route)
	return currentPageConfig
}


export async function getCurrentPageConfigByName(name) {
	const currentPageConfig = await getCurrentPageConfig()
	if (currentPageConfig && currentPageConfig.app_path_set) {
		return currentPageConfig.app_path_set.find(item => item.name === name)
	}
}


export async function getCurrentTemplateSubscribe() {
	const currentPageConfig = await getCurrentPageConfig()
	if (currentPageConfig && currentPageConfig.template_subscribe && currentPageConfig.template_subscribe.length) {
		return currentPageConfig.template_subscribe.map(item => item.wx_template_id)
	}
	return []
}
